<template>
  <div class="wrap wrap_map" :class="{ hide_pin: popShow}">
    <movable-area class="map_container" scale-area>
      <movable-view
        class="map_view"
        inertia
        animation
        scale
        scale-min="1"
        scale-max="2.5"
        :scale-value="rrrr_data.scale"
        direction="all"
        damping="30"
        friction="1"
        :x="rrrr_data.x"
        :y="rrrr_data.y"
        @change="mapMove"
        @scale="mapScale"
        @htouchmove="hTouch"
        :style="{width: mapInfo.width + 'px', height: mapInfo.height  + 'px'}">
        <img class="map_pic" @load="initMap" :src="imgSrc" />
        <div class="pin_info"
          :class="{
            hide: pinHide,
            pin_info_main: (item.level === 1 && item.rc_id !== 7),
            pin_info_special: (item.rc_id === 2 || item.rc_id === 3 || item.rc_id === 4 || item.rc_id === 5),
            pin_info_custom: item.rc_id === 7
            }"
          v-for="item in resources" :key="item.r_id"
          :style="{left: item.x / initScale - 16 + 'px', top: item.y / initScale - 34 + 'px', transform: 'scale(' + (1 / scale) + ') translateZ(0)'}"
          @click="resClick(item.r_id)">
          <div class="pin_icon">
            <img class="icon_bg" src="/static/img/icon_pin.svg" alt="" />
            <img v-if="item.rc_id === 7" class="icon_custom" :src="item.thumb" alt="" />
            <div class="iconfont"
                :class="{
                'icon-zsscenery': !item.is_have_audio && item.rc_id == 1,
                'icon-zsexplain': item.is_have_audio,
                'icon-zswc': item.rc_id == 5,
                'icon-zsservice': item.rc_id == 3,
                'icon-zsparking': item.rc_id == 4,
                'icon-zsexit': item.rc_id == 2,
                'icon-zssound': audio.show && audio.resId == item.r_id
                }"></div>
          </div>
          <div class="pin_title">{{item.r_title}}</div>
        </div>

        <div class="pin_mine" :style="{left: mine.x + 'px', top: mine.y + 'px', transform: 'scale(' + 1 / (scale) + ') translateZ(0)'}">
          <img   src="/static/img/gps.png"/>
        </div>

      </movable-view>
    </movable-area>



    <div class="mod_tips" :class="{none: !audio.show}">
      <img src="/static/img/wave.gif" alt="" class="icon_wave">
      <!-- <div class="iconfont icon-zssound"></div> -->
      <span class="text" @click="toAudioDetail">正在播放 {{audio.title}}</span>
      <div class="btn_close" title="关闭" @click="closeAudio">
        <div class="iconfont icon-zsclose"></div>
      </div>
    </div>

    <div class="pop_mask" v-show="popShow"  @click="hiddPop()"></div>
    <div class="pop_box" v-show="popShow" :class="{pop_box_nobtn: !popInfo.is_have_audio && !popInfo.is_need_pay && !popInfo.is_need_yy}">
      <div class="pop_close" @click="hiddPop()">
        <div class="iconfont icon-zsclose"></div>
      </div>
      <div class="pop_inner">
        <div class="title" :class="{title_narrow: popInfo.is_sign_in}">{{popInfo.r_title}}</div>
        <div class="btn_checkin" :class="{none: popInfo.is_sign_in !== 1}" @click="signInRes">
          <i class="iconfont icon-zssignon"></i>
          <template v-if="popInfo.is_have_sign_in === 0">签到</template>
          <template v-else>已签到</template>
        </div>
        <div class="content"  @click="toDetail">
          <img :src="popInfo.thumb" alt="" class="pic" />
          <div class="desc">
            {{popInfo.r_info}}
            <div class="desc_more">详情<div class="iconfont icon-zsinto"></div></div>
          </div>
        </div>
        <div class="btn_line">
          <div v-show="popInfo.is_have_audio"  @click="toDetail" class="btn_large green"><i class="iconfont icon-zsexplain"></i>讲解</div>
          <div v-show="popInfo.is_need_pay" class="btn_large blue" @click="toDetail"><i class="iconfont icon-zsticket"></i>门票</div>
          <div v-show="popInfo.is_need_yy" class="btn_large blue" @click="toDetail"><i class="iconfont icon-zsticket"></i>预约</div>
        </div>
      </div>
    </div>

    <div class="map_type">
      <button class="btn_item" :class="{current: resType === 5}" title="厕所" @click="showRes(5)">
        <div class="iconfont icon-zswc"></div>
        <span class="text">厕所</span>
      </button>
      <button class="btn_item" :class="{current: resType === 3}" title="服务点" @click="showRes(3)">
        <div class="iconfont icon-zsservice"></div>
        <span class="text">服务点</span>
      </button>
      <button class="btn_item" :class="{current: resType === 4}" title="停车场" @click="showRes(4)">
        <div class="iconfont icon-zsparking"></div>
        <span class="text">停车场</span>
      </button>
      <button class="btn_item" :class="{current: resType === 2}" title="出口" @click="showRes(2)">
        <div class="iconfont icon-zsexit"></div>
        <span class="text">出入口</span>
      </button>
    </div>

    <div class="mylocation" @click="showMyLocation()">
      <img src="/static/img/zslocation.svg" alt="" class="icon" />
      <span class="text">当前位置</span>
    </div>

    <div class="pop_ticket" v-if="yyTicket && yyTicket.id">
      <div class="iconfont icon-zsticket"></div>
      <div class="text">{{yyTicket.title}}</div>
      <a :href="'/pages/goods-detail/main?id=' + yyTicket.id" class="btn_em btn_yy_index">立即预约</a>
      <!--<button @click='goBaidu'>点击跳转</button>-->
      <!-- <a href="#" class="link">查看详情<i class="iconfont icon-zsinto"></i></a> -->
    </div>

    <div class="pop_toast" v-if="toastState">
      <div class="toast_inner">
        <div class="iconfont icon-zswarning"></div>
        <div class="toast_text">当前不在景区内</div>
      </div>
    </div>

    <div class="pop_modal" :class="{none: !showLogin}" catchtouchmove="moveMask">
      <div class="pop_modal_inner">
        <div class="modal_title">是否登录并继续使用该程序</div>
        <div class="modal_desc">登录程序需进行微信授权</div>
        <div class="modal_btns">
          <div class="btn_normal" @click="closeLogin">拒绝</div>
          <button class="btn_em" open-type="getUserInfo" @getuserinfo="onGotUserInfo">去登陆</button>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import fly from '@/utils/fly'
import { getOpenid } from '@/utils/login'
import { reportData } from '@/utils/report'
import debounce from '@/utils/debounce'
import utils from '@/utils/util'

let resMap = {}
let resArr = []
const GOODS = 1
const backgroundAudioManager = wx.getBackgroundAudioManager()

export default {
  data () {
    return {
      imgSrc: '',
      resources: [],
      deviceInfo: {
        width: 375,
        height: 660
      },
      mapInfo: {
        width: 1,
        height: 1
      },
      rrrr_data: {
        x: 0,
        y: 0,
        scale: 1
      },
      scale: 1,
      initScale: 1,
      popInfo: {},
      popShow: false,
      resType: GOODS,
      audio: {
        show: false,
        title: ''
      },
      mine: {
        x: -100,
        y: -100
      },
      yyTicket: {
        title: '',
        id: 0
      },
      toastState: false,
      pinHide: false,
      showLogin: false,
      from: ''
    }
  },
  watch: {
    scale (newVal, oldVal) {
      if (this.resType === GOODS && ((oldVal < 2 && newVal >= 2) || (oldVal >= 2 && newVal < 2))) {
        this.showRes(GOODS)
      }
    }
  },
  methods: {
    goBaidu () {
      wx.navigateTo({
        url: '/pages/outer/main'
      })
    },
    async getIndexInfo () {
      let openid = await getOpenid()
      let res = await fly.post(`Index/index?wx_openid=${openid}`)
      if (res && res.code === 200 && res.data) {
        if (res.data.yy_info && res.data.yy_info.yy_goods_id) {
          this.yyTicket = {
            title: res.data.yy_info.yy_title,
            id: res.data.yy_info.yy_goods_id
          }
        }
        resArr = res.data.res_list
        resArr.forEach(item => {
          if (item.rc_id === GOODS || item.rc_id === 7) {
            if (resMap[GOODS + '_' + item.level]) {
              resMap[GOODS + '_' + item.level].push(item)
            } else {
              resMap[GOODS + '_' + item.level] = [item]
            }
          } else {
            if (resMap['' + item.rc_id]) {
              resMap['' + item.rc_id].push(item)
            } else {
              resMap['' + item.rc_id] = [item]
            }
          }
        })
      } else {

      }
    },
    async signInRes () {
      if (this.popInfo.is_have_sign_in === 1) {
        return
      }
      let openid = await getOpenid()
      let rid = this.popInfo.r_id
      let res = await fly.post(`User/signIn?r_id=${rid}&wx_openid=${openid}`)
      if (res && res.code === 200 && res.data) {
        this.popInfo.is_have_sign_in = 1
        wx.showToast({
          title: '签到成功'
        })
      } else {

      }
    },
    mapMove: function (e) {
      // console.log('mapMove ', e)
      wx.setStorageSync('mapX', e.target.x)
      wx.setStorageSync('mapY', e.target.y)
    },
    mapScale: debounce(function (e) {
      // console.log('map sacle ', e)
      this.pinHide = false
      this.scale = e.target.scale
      wx.setStorageSync('mapX', e.target.x)
      wx.setStorageSync('mapY', e.target.y)
      wx.setStorageSync('mapScale', e.target.scale)
    }, 200, function () {
      this.pinHide = true
    }),
    getSystemInfo () {
      var res = wx.getSystemInfoSync()
      this.deviceInfo.width = res.windowWidth
      this.deviceInfo.height = res.windowHeight
    },
    setMap (x, y, scale) {
      console.log('setMap', x, y, scale)
      this.rrrr_data.x = -x
      this.rrrr_data.y = -y
      this.rrrr_data.scale = scale || 1
    },
    async initMap (event) {
      let { height, width } = event.target
      this.mapInfo.width = this.deviceInfo.height * width / height
      this.mapInfo.height = this.deviceInfo.height

      this.initScale = width / this.mapInfo.width

      wx.hideLoading()

      let res = await this.getLocation()
      if (res && res.code === 200 && res.data) {
        if (res.data.fixed_x === -1 && res.data.fixed_y === -1) {
          this.setMap(this.deviceInfo.height * width / (height * 2) - this.deviceInfo.width / 2, 0)
        }
      }
    },
    showRes (type) {
      if (Object.keys(resMap).length === 0) {
        return
      }
      if (type !== GOODS) {
        if (type === this.resType) {
          type = 1
        }
      }
      this.resType = type
      let rt = type
      let resTmp = []
      if (type === GOODS) {
        rt = type + '_' + 1
        resTmp = resMap['' + rt]

        if (this.scale >= 2) {
          rt = type + '_' + 2
          resTmp = resTmp.concat(resMap['' + rt])
        }
      } else {
        resTmp = resMap['' + rt]
      }
      this.resources = resTmp.map(item => {
        return {
          r_id: item.r_id,
          x: item.x,
          y: item.y,
          r_title: item.r_title,
          is_have_audio: item.is_have_audio,
          rc_id: item.rc_id,
          thumb: item.thumb,
          level: item.level,
          _length: item.r_title.replace(/[^\x00-\xff]/g, '01').length / 2
        }
      })
    },
    resClick (rid) {
      if (this.pinHide) {
        return false
      }
      let info = resArr.find(e => {
        return e.r_id === rid
      })
      if (!info.is_icon) {
        return
      }
      this.popShow = true
      this.popInfo = resArr.find(e => {
        return e.r_id === rid
      })

      reportData({
        funcx: '地图-气泡弹窗',
        keyx: rid
      })
    },
    hiddPop () {
      this.popShow = false
    },
    toDetail () {
      wx.navigateTo({
        url: '/pages/detail/main?id=' + this.popInfo.r_id
      })
    },
    async getLocation () {
      let openid = await getOpenid()
      let getLocation = function () {
        return new Promise((resolve, reject) => {
          wx.getLocation({
            success: function (res) {
              // wx.showToast({
              //   icon: 'none',
              //   title: '位置信息: ' + res.latitude + ', ' + res.longitude
              // })
              resolve(res)
            },
            fail: function (e) {
              wx.showToast({
                icon: 'none',
                title: '位置信息获取失败'
              })
              reject(e)
            }
          })
        })
      }
      let location = await getLocation()
      let res = await fly.post(`InfoReport/location?wx_openid=${openid}&longitude=${location.longitude}&latitude=${location.latitude}`)
      if (res && res.code === 200 && res.data) {
        // res.data.fixed_x = 0.169303
        // res.data.fixed_y = 0.608848
        let width = res.data.fixed_x * this.mapInfo.width - 9
        let height = res.data.fixed_y * this.mapInfo.height - 9
        this.mine = {
          x: width,
          y: height
        }
        if (res.data.fixed_x === -1 && res.data.fixed_y === -1) {
          console.log('location not in here')
        } else {
          this.$nextTick(function () {
            let that = this
            setTimeout(function () {
              let x = width * that.scale - that.deviceInfo.width / 2
              let y = height * that.scale - that.deviceInfo.height / 2
              // console.log('======', x, y)
              if (x > -9) {
                x = x + 9 + Math.random()
              }
              if (y > -9) {
                y = y + 9 + Math.random()
              }
              that.setMap(x, y)
            })
          })
        }
      }
      return res
    },
    async showMyLocation () {
      let res = await this.getLocation()
      if (res && res.code === 200 && res.data) {
        if (res.data.fixed_x === -1 && res.data.fixed_y === -1) {
          this.showToast()
        }
      }
    },
    closeAudio () {
      backgroundAudioManager.stop()
      this.audio.show = false
    },
    showToast () {
      var that = this
      this.toastState = true
      setTimeout(() => {
        that.hideToast()
      }, 3000)
    },
    hideToast () {
      this.toastState = false
    },
    toAudioDetail () {
      wx.navigateTo({
        url: '/pages/detail/main?id=' + this.audio.resId
      })
    },
    hTouch (e) {
      // console.log(e)
    },
    closeLogin () {
      this.showLogin = false
    },
    onGotUserInfo (res) {
      this.showLogin = false
      if (res && res.target && res.target.userInfo) {
        this.reportUser(res.target.userInfo)
      }
    },
    async reportUser (user) {
      let openid = await getOpenid()
      fly.post(`User/authorize?wx_openid=${openid}&u_img=${user.avatarUrl}&u_nickname=${user.nickName}`)
    },
    moveMask () {

    }
  },
  async onLoad (options) {
    wx.showLoading({
      title: '加载中'
    })
    // this.imgSrc = 'https://ssl.zhanglei.xyz/Uploads/map/img/map.min.jpg?new3'
    this.imgSrc = '/static/img/map2.min.jpg'
    this.getSystemInfo()
    await this.getIndexInfo()
    this.showRes(GOODS)
    let that = this

    let scene = decodeURIComponent(options.scene || '')
    if (scene) {
      let _from = scene.replace('?', '').replace(/&id=\d+/, '').replace(/^id=\d+/, '')
      this.from = _from
    }

    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (res) {
              that.reportUser(res.userInfo)
            }
          })
        } else {
          // 需要授权
          that.showLogin = true
          console.log('-- need user auth --')
        }
      }
    })
    let q = decodeURIComponent(options.q || '')
    if (q) {
      this.from = utils.getQueryString(q, 'from')
    }
    reportData({
      funcx: '地图首页',
      keyx: 0,
      from: this.from
    })
    this.from = ''
  },
  async onShow (options) {
    let audioInfo = this.$root.$mp.appOptions._audioInfo
    let that = this

    if (audioInfo && !backgroundAudioManager.paused) {
      this.audio.show = true
      this.audio.title = audioInfo.title
      this.audio.resId = audioInfo.resId
    } else {
      this.audio.show = false
    }

    backgroundAudioManager.onEnded(res => {
      that.audio.show = false
    })

    // 里面签到这里也更新状态
    if (this.popShow && this.popInfo.r_id && this.popInfo.is_have_sign_in === 0) {
      this.popInfo.is_have_sign_in = !this.$root.$mp.appOptions['_resSign_' + this.popInfo.r_id] ? 0 : 1
    }

    try {
      let _x = wx.getStorageSync('mapX')
      let _y = wx.getStorageSync('mapY')
      let _scale = wx.getStorageSync('mapScale')

      if (_scale) {
        this.scale = _scale
      }

      if ((_x || _x === 0) && (_y || _y === 0)) {
        this.setMap(_x * -1, _y * -1, _scale)
      }
    } catch (error) {
      console.log('---', error)
    }

    setTimeout(function () {
      reportData({
        funcx: '地图首页',
        keyx: 0,
        from: that.from
      })
      that.from = ''
    }, 200)
  },
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      console.log(res.target)
    }
  }
}
</script>

<style lang="scss">
  @import './index.scss';
</style>
